package com.joshua.spring.gateway.exception;

import com.joshua.spring.exception.MicroServiceException;
import com.joshua.spring.entity.em.ResponseEnum;
import com.joshua.spring.entity.vo.GlobalResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.Assert;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.function.server.ServerResponse.*;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.List;

/**
 * projectName dragon-cloud
 * package com.joshua.spring.gateway.exception
 * classname  GatewayJsonExceptionHandler
 * <p>
 * description 统一异常处理类
 * </p>
 * {@link AbstractErrorWebExceptionHandler}
 * {@link DefaultErrorWebExceptionHandler}
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/8/28 14:09
 */
@Slf4j
public class GatewayJsonExceptionHandler implements ErrorWebExceptionHandler {

    private List<HttpMessageReader<?>> messageReaders = Collections.emptyList();
    private List<HttpMessageWriter<?>> messageWriters = Collections.emptyList();
    private List<ViewResolver> viewResolvers = Collections.emptyList();
    /**
     * 存储处理异常后的信息
     */
    private ThreadLocal<GlobalResponse> exceptionHandlerResult = new ThreadLocal<>();

    /**
     * description:
     *
     * @param messageWriters {@link AbstractErrorWebExceptionHandler#setMessageWriters(List)} (List)}
     * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
     * @date 2020/8/28 14:20
     */
    public void setMessageWriters(List<HttpMessageWriter<?>> messageWriters) {
        Assert.notNull(messageWriters, "'messageWriters' must not be null");
        this.messageWriters = messageWriters;
    }

    /**
     * description:
     *
     * @param messageReaders {@link AbstractErrorWebExceptionHandler#setMessageReaders(List)}
     * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
     * @date 2020/8/28 14:20
     */
    public void setMessageReaders(List<HttpMessageReader<?>> messageReaders) {
        Assert.notNull(messageReaders, "'messageReaders' must not be null");
        this.messageReaders = messageReaders;
    }

    /**
     * description:
     *
     * @param viewResolvers {@link AbstractErrorWebExceptionHandler#setViewResolvers(List)}
     * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
     * @date 2020/8/28 14:20
     */
    public void setViewResolvers(List<ViewResolver> viewResolvers) {
        this.viewResolvers = viewResolvers;
    }

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        /**
         * 按照异常类型进行处理
         */
        GlobalResponse errorResponse;
        if (ex instanceof NotFoundException) {
            errorResponse = GlobalResponse.buildFail(ResponseEnum.SERVICE_UNAVAILABLE);
        } else if (ex instanceof MicroServiceException) {
            MicroServiceException gatewayException = (MicroServiceException) ex;
            errorResponse = gatewayException.getGlobalResponse();
        } else if (ex instanceof ResponseStatusException) {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            errorResponse = GlobalResponse.buildFail(responseStatusException.getStatus());
        } else {
            errorResponse = GlobalResponse.buildFail();
        }
        /**
         * 错误记录
         */
        ServerHttpRequest request = exchange.getRequest();
        log.error("Global exception handler,request path [{}], catch exception", request.getPath(), ex);
        /**
         * 参考AbstractErrorWebExceptionHandler
         */
        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }
        exceptionHandlerResult.set(errorResponse);
        ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
                .switchIfEmpty(Mono.error(ex))
                .flatMap((handler) -> handler.handle(newRequest))
                .flatMap((response) -> write(exchange, response));
    }

    protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
        GlobalResponse errorResponse = exceptionHandlerResult.get();
        return ServerResponse.status(HttpStatus.valueOf(errorResponse.getStatus()))
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(BodyInserters.fromObject(errorResponse));
    }

    private Mono<? extends Void> write(ServerWebExchange exchange,
                                       ServerResponse response) {
        exchange.getResponse().getHeaders()
                .setContentType(response.headers().getContentType());
        return response.writeTo(exchange, new ResponseContext());
    }


    /**
     *
     */
    private class ResponseContext implements Context {
        private ResponseContext() {
        }

        @Override
        public List<HttpMessageWriter<?>> messageWriters() {
            return GatewayJsonExceptionHandler.this.messageWriters;
        }

        @Override
        public List<ViewResolver> viewResolvers() {
            return GatewayJsonExceptionHandler.this.viewResolvers;
        }
    }
}
